package com.example.pceb.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.pceb.entity.Achievement;
import com.example.pceb.mapper.AchievementMapper;
import com.example.pceb.service.AchievementService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

@Service
public class AchievementServiceImpl extends ServiceImpl<AchievementMapper, Achievement> implements AchievementService {
    @Override
    public List<Achievement> getByUsername(String username) {
        return this.lambdaQuery().eq(Achievement::getUsername, username).list();
    }

    public List<Achievement> searchAchievements(String keyword) {
        LambdaQueryWrapper<Achievement> wrapper = new LambdaQueryWrapper<>();

        if (keyword != null && !keyword.trim().isEmpty()) {
            wrapper.like(Achievement::getUsername, keyword)
                    .or()
                    .like(Achievement::getTitle, keyword);
        } else {
            wrapper.last("LIMIT 10"); // 默认随机展示 10 条
        }

        return list(wrapper);
    }

    //模糊搜索 6.30
    @Override
    public List<String> getSuggestions(String keyword) {
        // 查询匹配的成果标题
        List<String> titles = lambdaQuery()
                .like(Achievement::getTitle, keyword)
                .select(Achievement::getTitle)
                .list()
                .stream()
                .map(Achievement::getTitle)
                .distinct()
                .toList();

        // 查询匹配的用户名
        List<String> usernames = lambdaQuery()
                .like(Achievement::getUsername, keyword)
                .select(Achievement::getUsername)
                .list()
                .stream()
                .map(Achievement::getUsername)
                .distinct()
                .toList();

        // 合并并去重返回
        Set<String> all = new LinkedHashSet<>();
        all.addAll(usernames);
        all.addAll(titles);
        return new ArrayList<>(all);
    }
}


